﻿using System;
using System.Collections.Generic;
using System.Linq;
using Shop.Base.Entity;
using Shop.Base.Entity.Delete;
using Shop.Base.Entity.Insert;
using Shop.Base.Entity.Update;
using Shop.Base.Interface;
using Shop.Entity;
using Shop.Server;
using Shop.Tools;

namespace Shop.Base.Server
{
    public class SystemMenu : BaseServer<SystemMenuPo>, ISystemMenu
    {
        public List<SystemMenuPo> GetPage(string menuName, Guid? parentId, int isDel, int pageIndex, int pageSize, out int total)
        {
            total = 0;
            return db.Queryable<SystemMenuPo>().WhereIF(!menuName.IsNullOrEmpty(), $" MemuName like @MemuName ", new { name = $"%{menuName}%" })
                .WhereIF(isDel > -1, $" isDel = @isDel ", new { isDel = (isDel == 1) })
                .WhereIF(parentId.HasValue && !parentId.Value.IsEmptyGuid(), $" ParentId = @ParentId ", new { ParentId = parentId })
                .OrderBy("IndexNum").ToPageList(pageIndex, pageSize, ref total);
        }

        public List<SystemMenuPo> GetAll()
        {
            return  db.Queryable<SystemMenuPo>().OrderBy("IndexNum").ToList();
        }

        public bool Insert(AddSystemMenu t, ComUser com)
        {
            t.CreateId = com.Id;
            t.CreateName = com.UserName;
            var model = db.Queryable<SystemMenuPo>().Where(x => x.IsDel == false && x.IndexNum == t.IndexNum).First();
            if (t.IndexNum == 0 || (model != null && !model.Id.IsEmptyGuid()))
            {
                var maxSort = db.Queryable<SystemMenuPo>().Where(x => x.IsDel == false).Max(x => x.IndexNum);
                t.IndexNum = maxSort + 1;
            }
            return db.Insertable(t).ExecuteCommand() > 0;
        }

        public bool Update(UpdateSystemMenu t, ComUser com)
        {
            t.UpdateAt = DateTime.Now;
            t.UpdateId = com.Id;
            t.UpdateName = com.UserName;
            var model = db.Queryable<SystemMenuPo>().Where(x => x.IsDel == false && x.IndexNum == t.IndexNum && x.Id != t.Id).First();
            if (t.IndexNum == 0 || (model != null && !model.Id.IsEmptyGuid()))
            {
                var maxSort = db.Queryable<SystemMenuPo>().Where(x => x.IsDel == false).Max(x => x.IndexNum);
                t.IndexNum = maxSort + 1;
            }
            return db.Updateable(t).ExecuteCommand() > 0;
        }
    }
}